package com.example.administrator.testxingpiao.utils;

import android.content.Context;

import android.util.Log;

import com.example.administrator.testxingpiao.ui.city.City;
import com.github.promeg.pinyinhelper.Pinyin;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/7.
 */
public class JsonUtil {

    public static String getLocalJson(Context context){
        String line = "";
        String json = "";
        InputStream is = context.getClass().getClassLoader().getResourceAsStream("assets/city.json");
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                json += line.trim();
                //log("while里：json" + json);
            }
            log("while外：json+" + json);
            return json.trim();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static List<City> getCityList(final Context context){
        final List<City> mList = new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = getLocalJson(context);
                log("jinru---->getCityList" + json);
                JSONArray array = null;
                try {
                    array = new JSONArray(json);
                    for(int i = 0;i < array.length();i++){
                        JSONArray cityArray = array.getJSONObject(i).getJSONArray("city");
                        for(int j = 0;j < cityArray.length();j++){
                            String name = cityArray.getJSONObject(j).getString("name");
                            City city = new City();
                            city.setCityName(name);
                            log("name=" + name);
                            city.setCityPinyin(transformPinYin(name));
                            mList.add(city);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return mList;
    }
    public static String transformPinYin(String character) {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < character.length(); i++) {
            buffer.append(Pinyin.toPinyin(character.charAt(i)));
        }
        return buffer.toString();
    }

    public static void log(String msg){
        Log.i("TAG",msg);
    }
}
